/**
 * @filename server.js
 *
 * @module
 *
 * @author Justin <zhou78620051@126.com>
 * @version 1
 * @time 2017/2/1 0:22
 */

"use strict";

const WebSocket = require('ws');

const wss = new WebSocket.Server({
    perMessageDeflate: false,
    port: 3000
});

// Broadcast to all.
wss.broadcast = function broadcast(data) {
    wss.clients.forEach(function each(client) {
        if (client.readyState === WebSocket.OPEN) {
            client.send(data);
        }
    });
};

wss.on('connection', function connection(ws) {
    ws.on('message', function incoming(data) {
        // Broadcast to everyone else.
        wss.clients.forEach(function each(client) {
            if (client !== ws && client.readyState === WebSocket.OPEN) {
                client.send(data);
            }
        });
    });
});

setInterval(function(){
    wss.broadcast(JSON.stringify({
        "timestamp": new Date().valueOf()
    }));
},50);